import Vue from 'vue'
import { deepCopy, setPage } from '@/utils/util'
import fetch from '@/utils/network/fetch'
import formPost from '@/utils/network/formPost'
import { Message } from 'element-ui'

const initPage = {
    size: 10,
    number: 0,
    total: 0,
    pages: 0,
    filter: {
        enabled: null,
        title: null
    }
}

// state
const state = {
    data: {
        imageVerifyCode: null,
        loginUser: Vue.ls.get('loginUser')
    },
    ui: {
        page: deepCopy(initPage)
    }
}

// getter
const getters = {
    imageVerifyCode: state => state.data.imageVerifyCode,
    loginUser: () => state.data.loginUser ? state.data.loginUser : Vue.ls.get('loginUser'),
    userInfo: () => state.data.loginUser && state.data.loginUser.userInfo ? state.data.loginUser.userInfo : Vue.ls.get('loginUser') ? Vue.ls.get('loginUser').userInfo : {}
}

// actions
const actions = {
    getImageVerifyCode({ commit }) {
        fetch('/api/user/code', {
            success: imageInfo =>
                commit('setImageVerifyCode', { imageVerifyCode: imageInfo.imageBase64 })
        })
    },
    checkImageVerifyCode({ dispatch }, objc) {
        fetch(`/api/user/code/${objc.code}`, {
            showError: true,
            success: imageInfo => {
                if (imageInfo.code === 200) {
                    objc && objc.success && objc.success(imageInfo)
                } else {
                    dispatch('getImageVerifyCode')
                    Message({
                        center: true,
                        type: 'error',
                        message: '验证码不正确'
                    })
                }
            }
        })
    },
    formLogin({ commit }, objc) {
        formPost('api/user/formlogin', {
            showError: true,
            data: `username=${objc.data.username}&password=${objc.data.password}&remember-me=${
                objc.data.rememberMe
                }`,
            success: user => {
                commit('setLoginUserInfo', user)
                objc && objc.success && objc.success(user)
            }
        })
    },
    logout({}, objc) {
        fetch('/api/user/logout', {
            success: () => {
                Vue.ls.remove('loginUser')
                objc && objc.success && objc.success()
            }
        })
    }
}

// mutations
const mutations = {
    setImageVerifyCode: (state, payload) => {
        state.data.imageVerifyCode = payload.imageVerifyCode
    },
    setLoginUserInfo: (state, payload) => {
        let sessionLoginUser = Vue.ls.get('loginUser')
        const loginUser = { ...state.data.loginUser, ...sessionLoginUser, ...payload}
        Vue.ls.set('loginUser', loginUser)
        state.data.loginUser = loginUser
    }
}

export default {
    state,
    getters,
    actions,
    mutations
}
